#include<iostream>
#include<string>

#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>

#include<cerrno>
#include<cstring>
#include"Log.hpp"
#include"Comm.hpp"
#include<strings.h>

//  ./udp_server server_ip server_port

void Usage(const std::string &proc)
{
    std::cout<<"Usage: "<<proc<<" server_ip server_port "<<std::endl;
}

int main(int argc,char* argv[])
{
    if(argc!=3)
    {
        Usage(argv[0]);
        exit(Usage_Err);
    }
    const std::string serverip=argv[1];
    uint16_t serverport=std::stoi(argv[2]);
    //创建套接字
    int sock=socket(AF_INET,SOCK_DGRAM,0);
    if(sock<0)
    {
        lg.LogMessage(Fatal,"socket errr, %d : %s",errno,strerror(errno));
        exit(Socket_Err);
    }
    lg.LogMessage(Info,"socket success,sockfd: %d\n",sock);


    struct sockaddr_in server;
    bzero(&server,sizeof(server));
    server.sin_family=AF_INET;
    server.sin_addr.s_addr=inet_addr(serverip.c_str());
    server.sin_port=htons(serverport);

    //发送数据
    while (true)
    {
        std::string buff;
        std::cout<<"Please Enter# ";
        getline(std::cin, buff);
        socklen_t serverlen = sizeof(server);
        ssize_t n = sendto(sock, buff.c_str(), buff.size(), 0, (struct sockaddr *)&server, serverlen);
        if (n > 0)
        {
            char buf[1024];
            struct sockaddr_in temp;
            socklen_t len = sizeof(server);
            ssize_t m=recvfrom(sock, &buf, sizeof(buf)-1, 0, (struct sockaddr *)&temp, &len);
            if(m>0)
            {
                buf[m]=0;
                std::cout <<"server echo# "<< buf << std::endl;
            }
            else
            {
                break;
            }
        }
        else
        break;
    }
    close(sock);
    return 0;
}